package org.tea.mapper.util;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.builder.annotation.ProviderContext;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.logging.LogFactory;

import java.util.List;

/**
 *@author lxh
 */
@Mapper
public class BaseDeleteMapperProvider
        extends MapperHelper {

    private final static Log log = LogFactory.getLog(BaseDeleteMapperProvider.class);

    public String deleteByPrimaryKey(Object primaryKey, ProviderContext providerContext) {
        Class<?> entityType = parseActualEntityType(providerContext.getMapperType());
        String tableName = parseTableName(entityType);
        List<String> pkColumns = parsePrimaryKeyColumns(entityType);

        StringBuilder deleteSqlBuilder = new StringBuilder();
        deleteSqlBuilder.append("DELETE FROM ").append(tableName).append("\n")
                .append("WHERE ")
                .append(pkColumns.get(0)).append("='").append(primaryKey).append("'");
        log.trace(String.format("deleteByPrimaryKey actual sql: %s", deleteSqlBuilder));
        return deleteSqlBuilder.toString();
    }

    public String deleteRows(List<?> deletedRows, ProviderContext providerContext) {
        Class<?> entityType = parseActualEntityType(providerContext.getMapperType());
        String tableName = parseTableName(entityType);

        StringBuilder deleteSqlBuilder = new StringBuilder();
        deleteSqlBuilder.append("<script>")
                .append("DELETE FROM ").append(tableName).append("\n")
                .append(buildUpdateWhereSql(entityType, deletedRows))
                .append("</script>");
        log.trace(String.format("deleteRows actual sql: %s", deleteSqlBuilder));
        return deleteSqlBuilder.toString();
    }
}
